package com.wx.controller;

import com.google.code.kaptcha.Producer;
import com.wx.common.WrapMapper;
import com.wx.common.Wrapper;
import com.wx.constants.RedisKeyPrefix;
import com.wx.service.RedisService;
import com.wx.service.ValidateCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

/**
 * <p>Title:      SysLoginController. </p>
 * <p>Description TODO </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:     医百科技有限公司</p>
 *
 * @author <a href="xinglinglove1029@163.com"/>杨文生</a>
 * @since 2019/8/14 22:20
 */
@RestController
@RequestMapping(value = "/validateCode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(tags = "验证码管理", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SysValidateCodeController {

    @Resource
    private Producer defaultKaptcha;

    @Resource
    private RedisService redisService;

    @Resource
    private ValidateCodeService validateCodeService;



    /**
     * <p>Title:      generateValidateCode. </p>
     * <p>Description 生成验证码</p>
     *
     * @param httpServletRequest HttpServletRequest
     * @return void
     * @Author <a href="xinglinglove1029@163.com"/>杨文生</a>
     * @since 2019/8/16 23:19
     */
    @ApiOperation("生成图片验证码")
    @GetMapping(value = "/generateValidateCode")
    public Wrapper<String> generateValidateCode(HttpServletRequest httpServletRequest) throws Exception {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        // 生产验证码字符串并保存到redis中
        String createText = defaultKaptcha.createText();
        redisService.set(RedisKeyPrefix.LOGIN_PREFIX + httpServletRequest.getRemoteAddr(), createText, RedisKeyPrefix.EXPIRE_TIME_MINUTE);
        BufferedImage bufferedImage = defaultKaptcha.createImage(createText);
        ImageIO.write(bufferedImage, "jpg", jpegOutputStream);
        Base64.Encoder encoder = Base64.getEncoder();
        String base64 = encoder.encodeToString(jpegOutputStream.toByteArray());
        String captchaBase64 = "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, captchaBase64);
    }



    @PostMapping("/generateSmsCode/{mobile}")
    @ApiOperation(value = "生成短信验证码")
    public Wrapper<?> generateSmsCode(@PathVariable("mobile") String mobile) {
        String generateSmsCode = validateCodeService.generateSmsCode(mobile);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE,generateSmsCode);
    }


}
